<?php

class Wills
{
  static public function initLoginForm(sfActions $actions, sfForm $form)
  {
    $user    = $actions->getUser();
    $request = $actions->getContext()->getRequest();

    if ($actions->getContext()->getActionStack()->getSize() > 1)
    {
      $user->setAttribute('referer', $request->getUri());
      $request->setParameter('sf_warning', '您必须登陆才能访问此页面');
      $actions->getResponse()->setStatusCode(401);
    }
    else
    {
      $user->setAttribute('referer', $request->getReferer());
    }

    $actions->form = $form;
  }

  static public function processLogin(sfActions $actions, sfForm $form)
  {
    $request = $actions->getContext()->getRequest();
    $user    = $actions->getUser();

    $actions->forward404Unless($request->isMethod(sfRequest::POST));

    $actions->form = $form;
    $actions->form->bind($request->getParameter('session'));

    if ($actions->form->isValid())
    {
      $user->setFlash('message', '您已成功登陆');
      if ($redirect = $user->getAttribute('referer'))
      {
        $user->setAttribute('referer', null);
        $actions->redirect($redirect);
      }
      else
      {
        $actions->redirect('@homepage');
      }
    }
    else
    {
      $actions->setTemplate('new');
    }
  }

  static public function processLogout(sfActions $actions)
  {
    $request = $actions->getContext()->getRequest();
    $user    = $actions->getUser();

    $actions->forward404Unless($request->isMethod(sfRequest::DELETE));

    $user->setAttribute('id', null);
    $user->setAttribute('account', null);
    $user->clearCredentials();
    $user->setAuthenticated(false);
    $user->setFlash('message', '您已成功退出');

    $actions->redirect('@homepage');
  }
  
  static public function getUploadDirByWebPath($path)
  {
    return sfConfig::get('sf_web_dir') . preg_replace('/\/%s$/', '', $path);
  }
}
